/**
 * @author Stephan Pfaff (webmaster@derdaumen.net)
 */

/*
 * ############################################################################
 * ########################### ItemContainer Class ############################
 * ############################################################################
 */

function ItemContainer(type, prefix, urlLoad, urlSave, urlNew, urlDelete) {
	try {
		this.type = type;
		this.prefix = prefix;
		this.item_selector = '#select_'+type;
		this.position_selector = '#'+prefix+'_position';
		this.form = '#form_'+type;
		this.urlLoad = urlLoad;
		this.urlSave = urlSave;
		this.urlNew = urlNew;
		this.urlDelete = urlDelete;
		this.items = null;
		var handle = this;
		this.thumbUploader = $('#'+this.prefix+'_thumb_upload_container').swfupload({
			upload_url: "../lib/php/uploadTempImageToCrop.php",
			file_size_limit : maxImgSize,
			file_types : "*.jpg;*.png;*.gif;*.jpeg",
			file_types_description : "Web Image Files",
			file_upload_limit : "0",
			flash_url : "../lib/js/backend/plugins/swfUpload/swfupload.swf",
			button_image_url : '../css/backend/screen/images/swfupload.png',
			button_width : 61,
			button_height : 22,
			button_placeholder : $('#'+this.prefix+'_thumb_upload_btn')[0],
			debug: false
		})
			.bind('swfuploadLoaded', function(event){})
			.bind('fileQueued', function(event, file){
				// start the upload since it's queued
				$(this).swfupload('startUpload');
			})
			.bind('fileQueueError', function(event, file, errorCode, message){
				if(errorCode == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED)
					alert(message);
				if(errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT)
					alert('Fehler: Die Datei ist größer als '+maxImgSize);
				if(errorCode == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE)
					alert(message);
				if(errorCode == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE)
					alert(message);
			})
			.bind('fileDialogStart', function(event){})
			.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){})
			.bind('uploadStart', function(event, file){})
			.bind('uploadProgress', function(event, file, bytesLoaded, bytesTotal){
				$('#'+handle.prefix+'_progress_bar_inner').css({
					width: (bytesLoaded/bytesTotal)*100+'%'
				});
			})
			.bind('uploadSuccess', function(event, file, response){
				$('.swfupload').hide();
				handle.showCropDialog(file, response);
				$('#'+handle.prefix+'_progress_bar_inner').css({
					width: '0%'
				});
			})
			.bind('uploadComplete', function(event, file){})
			.bind('uploadError', function(event, file, errorCode, message){
				if(errorCode == SWFUpload.UPLOAD_ERROR.HTTP_ERROR)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.IO_ERROR)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.SECURITY_ERROR)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED)
					alert(message);
			});
	} catch(e) {
		if(debug) alert('Initialization of new ItemContainer failed, missing or wrong parameter! ('+e+')');
	}
};
ItemContainer.prototype.type = null;
ItemContainer.prototype.prefix = null;
ItemContainer.prototype.item_selector = null;
ItemContainer.prototype.position_selector = null;
ItemContainer.prototype.form = null;
ItemContainer.prototype.urlLoad = null;
ItemContainer.prototype.urlSave = null;
ItemContainer.prototype.urlNew = null;
ItemContainer.prototype.urlDelete = null;
ItemContainer.prototype.items = null;
ItemContainer.prototype.thumbUploader = null;

ItemContainer.prototype.getInstance = function() {
	switch(this.type) {
	case 'category':
		return getCategories();
	case 'project':
		return getProjects();
	case 'button':
		return getButtons();
	}
};
ItemContainer.prototype.length = function(){
	if (this.items != null) {
		var i = 0;
		for (key in this.items) {
			i++;
		}
		return i;
	} else {
		return 0;
	}
};
ItemContainer.prototype.currentItem = function(){
	if(this.items[this[0].value] != null) {
		return this.items[this[0].value];
	} else {
		return null;
	}
};
ItemContainer.prototype.prevItem = function(){
	return this.items[this.prevOption().val()];
};
ItemContainer.prototype.nextItem = function(){
	return this.item[this.nextOption().val()];
};
ItemContainer.prototype.currentOption = function(){
	return $(this.item_selector+' option:selected');
};
ItemContainer.prototype.prevOption = function(){
	return $(this.item_selector + ' option:selected').prev();
};
ItemContainer.prototype.nextOption = function(){
	return $(this.item_selector + ' option:selected').next();
};
ItemContainer.prototype.change = function(event) {
	this.currentItem().select(event);
};
ItemContainer.prototype.hideErrorMessages = function () {
	$(this.form).hideErrorMessages();
};
ItemContainer.prototype.clearFormElements = function (empty_selector) {
	if(empty_selector) {
		$(this.item_selector).empty();
	}
	$(this.form).clearForm();
};
ItemContainer.prototype.preSelect = function(preSelection, autoSelect){
	//wenn übergeben, preselected item fokussieren
	if (preSelection != null) {
		this[0].selectedIndex = this.items[preSelection].position;
		$(this.item_selector).val($(this.item_selector +
				' option[value="'+preSelection+'"]').val()).focus().change();
	//anderfalls, wenn autoSelect = true, das erste element fokussieren
	} else if (autoSelect) {
		$(this.item_selector).val($(this.item_selector + ' option:first').val())
			.focus().change();
	} else {
		this.clearFormElements(false);
	}
};

ItemContainer.prototype.show = function(preSelection, autoSelect){
	if (this.length() > 0) {
		//die select-box leeren
		$(this.item_selector).empty();
		//falls positions-box vorhanden, diese leeren
		if (this.position_selector != null) {
			$(this.position_selector).empty();
		}
		var i = 0;
		for(key in this.items) {
			//select-box mit optionen füllen 
			$(this.item_selector).append('<option value="'+key+'" >'
					+this.items[key].alias+'</option>'+'\n');
			//optional position-box füllen
			if (this.position_selector != null) {
				$(this.position_selector).append('<option value="'+i+'" >'
						+(i+1)+'</option>'+'\n');
			}
			i++;
		}
		this.preSelect(preSelection, autoSelect);
	} else {
		this.clearFormElements(true);
	}
};
ItemContainer.prototype.fillItems = function(items_temp, preSelection, autoSelect) {
	//index des items im options array des select-elements
	for(key in items_temp) {
		//Die geladenen Objekte erstellen und in items speichern
		switch (this.type) {
		case 'category':
			this.items[key] = new Category(items_temp[key]);
			break;
		case 'project':
			this.items[key] = new Project(items_temp[key]);
			break;
		case 'button':
			this.items[key] = new Button(items_temp[key]);
			break;
		}
	}
	//preface einfügen
	if (this.type == 'category') {
		var preface = {
				type: 'category',
				basename: 'preface',
				path: '/preface/',
				prefix: 'ctg',
				id: 0,
				alias: 'preface',
				label: 'Preface',
				thumb: '',
				thumb_enable: false,
				start_x: 0,
				start_y: 0,
				position: this.length()
		};
		this.items[0] = new Category(preface);
	}
	if (this.length() > 0) {
		this.show(preSelection, autoSelect);
	} else {
		this.clearFormElements(true);
	}
};
/**
 * Lädt Item-Daten aus der Datenbank, instanziiert damit Item-Objekte
 * die im Item-Container-Objekt gespeichert und anschließend angezeigt werden.
 * 
 * @param params 		Parameter Objekt: {prefix, ctg_id und prj_id}
 * @param preSelection	ID des Items das nach dem laden ausgewählt werden soll.
 * @param autoSelect	Automatische auswahl des ersten Items wenn true
 * @return
 */
ItemContainer.prototype.load = function(params, preSelection, autoSelect) {
	this.items = new Object();
	var handle = this;
	$.getJSON(this.urlLoad, params, function(response){
		//wenn anfrage erfolgreich und items nicht leer
		if(response.result && response.items != null) {
			handle.fillItems(response.items, preSelection, autoSelect);
		} else {
			if(debug) alert('load ' + handle.type + ' failed:\n'
					+ 'error: ' +response.error +"\n"
					+ 'items: ' +response.items +"\n"
					+ 'itemContainer: ' +($(handle.item_selector).length > 0));
		}
	});
};

ItemContainer.prototype.newItem = function() {
	var item = null;
	switch (this.type) {
	case 'category':
		var item = new Category();
		break;
	case 'project':
		var item = new Project();
		break;
	case 'button':
		var item = new Button();
		break;
	}
	if (this.items == null) {
		this.items = new Object();
		this.items[item.id] = item;
	} else {
		this.items[item.id] = item;
	}
	item.position = this.length()-1;
	this.show(item.id, false);
};

/**
 * Saves the currentItem selected item to the database and reloads 
 * all items afterwards.
 * 
 * @return
 */
ItemContainer.prototype.saveItem = function() {
	//if(this.currentItem().check()){
	if(true) {
		if(this.currentItem().assignValues()) {
			var prefix = this.prefix;
			var ctg_id = this.currentItem().category_id;
			var prj_id = this.currentItem().project_id;
			var handle = this;
			if(this.currentItem().id > 0) {
				//existierendes Item updaten
				$.post(this.urlSave,
						{data: this.currentItem().encodeToJSON()},
						function(response) {
							if(response.result) {
								handle.load({prefix: prefix,
									ctg_id: ctg_id,
									prj_id: prj_id},
									response.id, false);
								alert(handle.type+' gespeichert.');
							} else {
								alert('Save '+handle.type+' failed: '+response.error);
							}
						}, 'json');
			} else {
				//neues Item speichern
				$.post(this.urlNew,
						{data: this.currentItem().encodeToJSON()},
						function(response) {
							console.dir(response);
							if(response.result) {
								handle.load({prefix: prefix,
									ctg_id: ctg_id,
									prj_id: prj_id},
									response.id, false);
								alert(handle.type+' gespeichert.');
							} else {
								alert('Save new '+handle.type+' failed: '+response.error);
							}
						}, 'json');
			}
		}
	} else {
		alert("Eines der rot markierten Felder ausfüllen!");
	}
};
/**
 * Setzt das ausgewählte Item aus seinen zuletzt gespeicherten Stand zurück.
 * 
 * @return
 */
ItemContainer.prototype.resetItem = function(){
	this.currentItem().resetItem();
};
/**
 * Löscht das ausgewählte Item.
 * Alle Daten des Items, die Daten der Kind-Items sowie ihre zugehörigen
 * Bild-Dateien werden aus der Datenbank und vom Datenträger gelöscht.
 * 
 * @return
 */
ItemContainer.prototype.deleteItem = function(){
	var id = this.currentItem().id;
	var ctg_id = this.currentItem().category_id;
	var prj_id = this.currentItem().project_id;
	var prefix = this.prefix;
	var path = this.currentItem().path;
	var prevOption = $(this.prevOption()).val();
	var handle = this;
	
	$.getJSON(this.urlDelete, {prefix: prefix, id: id, path: path}, function(response){
		if(response.result) {
			handle.load({prefix: prefix, ctg_id: ctg_id, prj_id: prj_id}, prevOption, false);
			var errorString = 'Löschen erfolgreich:\n';
			if(response.result_files) 
				errorString += '- verknüpfte Dateien gelöscht.\n';
			else errorString += '- keine verknüpften Dateien gefunden.\n';
			if(response.result_categories)
				errorString += '- Kategorie gelöscht.\n';
			else errorString += '- keine Kategorie gelöscht.\n';
			if(response.result_projects)
				errorString += '- Projekte gelöscht.\n';
			else errorString += '- keine Projekte gelöscht.\n';
			if(response.result_buttons)
				errorString += '- Buttons gelöscht.\n';
			else errorString += '- keine Buttons gelöscht.\n';
			if(debug) alert(errorString);
		} else {
			var errorString = 'Delete '+handle.type+' failed: '+response.error+'\n';
			if(response.error_files != null) 
				errorString += 'Error while deleting associated files: ' + response.error_files+'\n';
			if(response.error_categories != null)
				errorString += 'Error while deleting categories: ' + response.error_categories+'\n';
			if(response.error_projects != null)
				errorString += 'Error while deleting projects: ' + response.error_projects+'\n';
			if(response.error_buttons != null)
				errorString += 'Error while deleting buttons: ' + response.error_buttons+'\n';
			if(debug) alert(errorString);
		}
	});
};
/**
 * Speichert für das asgewählte Item ein Thumbnail.
 * 
 * @return
 */
ItemContainer.prototype.saveThumb = function() {
	var path = this.currentItem().path;
	var handle = this;
	if($('.jcrop-holder').length > 0) {
		if(tempPath != '') {
			$.post("../lib/php/uploadThumb.php",
					{file: tempPath,
					folder: path,
					x: $('#img_crop_x').val(),
					y: $('#img_crop_y').val(),
					w: $('#img_crop_w').val(),
					h: $('#img_crop_h').val()},
					function(response){
						if (response.result) {
							$('#'+handle.prefix+'_thumb_path').val(response.pathname);
							/*$('#'+handle.prefix+'_thumb').attr('src',
									response.pathname+'?'+Math.floor(Math.random()*1001));*/
							$('#'+handle.prefix+'_thumb_enable').attr('checked', true);
							handle.saveItem();
						} else {
							alert('Fehler beim Erstellen des Thumbnails: '+response.error);
						}
					},
					"json");
		} else {
			alert('Kein Bild hochgeladen');
		}
	}
};
ItemContainer.prototype.showCropDialog = function(file, uploadResponse) {
	var response = jQuery.parseJSON(uploadResponse);
	if(response.result){
		if (response.pathname != null && response.pathname != '') {
			prepareCrop(response, true);
			cropDialog.container = this;
			$('#dialog_crop').dialog('open');
		}
	} else {
		if(debug) alert('Error while uploading image: '+response.error);
	}
};